<template>
  <div class="map-container">
    <div class="mapCheckedBox">
      <el-checkbox v-model="areaChecked" class="white-text-checkbox"
        >显示情报区域范围</el-checkbox
      >
    </div>
    <div ref="chartRef" class="chart-container"></div>

    <div class="mapTabs">
      <div
        class="tab"
        style="margin-left: -10px"
        @click="handleDetail('0')"
        :class="{ tabCur: currTabIndex == '0' }"
      >
        机场预测详情
      </div>
      <div
        class="tab tabs"
        @click="handleDetail('1')"
        :class="{ tabCur: currTabIndex == '1' }"
      >
        机场终端区预测详情
      </div>
      <div
        @click="handleDetail('2')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '2' }"
      >
        区域统计预测详情
      </div>
      <div
        @click="handleDetail('3')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '3' }"
      >
        航路态势预测详情
      </div>
      <div
        @click="handleDetail('4')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '4' }"
      >
        航路分时预测详情
      </div>
      <div
        @click="handleDetail('5')"
        class="tab tabs1"
        :class="{ tabCur: currTabIndex == '5' }"
      >
        航线分时预测详情
      </div>
    </div>
    <DetailAir
      v-if="currTabIndex == '0'"
      :airTestsObj="airTestsObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '0Spa'"
      :airTestsObj="airTestsObjSpa"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '1'"
      :airTestsObj="airTests1Obj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailAir
      v-if="currTabIndex == '1Spa'"
      :airTestsObj="airTestsObj1Spa"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailArea
      v-if="currTabIndex == '2'"
      :airTestsAreaObj="airTestsAreaObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailArea
      v-if="currTabIndex == '2Spa'"
      :airTestsAreaObj="airTestsArea2Obj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailRoute
      v-if="currTabIndex == '3'"
      :airTestsRouteObj="airTestsRouteObj"
      @update-curr-detail-index="handleTabChange"
    />
    <DetailFilter
      v-if="currTabIndex == '4' || currTabIndex == '5'"
      :airTestsFilterObj="airTestsFilterObj"
      @update-curr-detail-index="handleTabChange"
    />
    <NoDatas
      v-if="currTabIndex == '6'"
      @update-curr-detail-index="handleTabChange"
    />
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  computed,
  defineProps,
} from "vue";
import * as echarts from "echarts/core";
import { GeoComponent, TooltipComponent } from "echarts/components";
import { MapChart, LinesChart, ScatterChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import isValidValue from "@/utils/tools/isValidValue";
import DetailAir from "./detailAir.vue";
import DetailArea from "./detailArea.vue";
import DetailRoute from "./detailRoute.vue";
import DetailFilter from "./detailFilter.vue";
import NoDatas from "./noDatas.vue";
import { firApi } from "@/api/tabOne";

// 注册所需模块
echarts.use([
  GeoComponent,
  MapChart,
  ScatterChart,
  LinesChart,
  CanvasRenderer,
  TooltipComponent,
]);

// 1. 统一精度修正工具（处理NaN/undefined，避免计算异常）
const fixPrecision = (num) => {
  if (isNaN(num) || typeof num === "undefined") return 0;
  return Math.round(num * 10) / 10;
};

// 2. 接收父组件参数（确保默认值有效）
const props = defineProps({
  airports: {
    type: Array,
    default: () => [],
  },
  airports1: {
    type: Array,
    default: () => [],
  },
  airports2: {
    type: Array,
    default: () => [],
  },
  areaStatic: {
    type: Array,
    default: () => [],
  },
  areaStatic1: {
    type: Array,
    default: () => [],
  },
  routeWayPoints: {
    type: Array,
    default: () => [],
  },
  airTestsObj: {
    type: Object,
    default: () => ({}),
  },
  airTests1Obj: {
    type: Object,
    default: () => ({}),
  },
  airTestsAreaObj: {
    type: Array,
    default: () => [],
  },
  airTestsRouteObj: {
    type: Array,
    default: () => [],
  },
  airTestsFilterObj: {
    type: Array,
    default: () => [],
  },
});

// 3. 组件状态管理（所有变量都有初始值，避免未定义）
const currTabIndex = ref("");
const airTestsObjSpa = ref({});
const airTestsObj1Spa = ref({});
const airTestsArea2Obj = ref([]);
const areaChecked = ref(false);
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
const lineWidth = computed(() => 1); // 固定线宽，无需动态计算
const gridLines = ref([]);
const gridSize = ref(2.5); // 固定网格步长
const completeGridRange = ref({
  minLon: 67.5,
  maxLon: 142.5,
  minLat: 7.5,
  maxLat: 62.5,
}); // 默认网格范围（中国区域+缓冲）
const visibleRange = ref({
  minLon: 70,
  maxLon: 140,
  minLat: 10,
  maxLat: 60,
}); // 默认可视范围
const isFirstLoad = ref(true);
const pathData = ref([]);
const pathSeriesName = "simulatePath";

// 4. 防抖工具（无依赖，直接使用）
const debounce = (fn, delay = 300) => {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
};

// 5. 图例配置（逻辑闭环，无未使用变量）
const legendConfig = computed(() => {
  if (isValidValue(props.areaStatic)) {
    return [
      {
        type: "rect",
        right: 60,
        top: 20,
        zlevel: 5,
        shape: { width: 12, height: 12 },
        style: { fill: "#ff0000" },
      },
      {
        type: "text",
        right: 20,
        top: 20,
        zlevel: 5,
        style: { text: "不可用", fontSize: 12, fill: "#ffffff" },
      },
    ];
  } else if (isValidValue(props.areaStatic1)) {
    const legendItems = [
      { color: "#7cfa8d", text: "0", top: 20 },
      { color: "#4dad51", text: "1-5", top: 45 },
      { color: "#2f7132", text: "6-10", top: 70 },
      { color: "#d7fc62", text: "11-20", top: 95 },
      { color: "#fcfe54", text: "21-30", top: 120 },
      { color: "#f8cf59", text: "31-40", top: 145 },
      { color: "#f19135", text: "41-50", top: 170 },
      { color: "#ee692c", text: "51-60", top: 195 },
      { color: "#ec3323", text: ">60", top: 220 },
    ];
    return legendItems.flatMap((item) => [
      {
        type: "rect",
        right: 60,
        top: item.top,
        zlevel: 5,
        shape: { width: 12, height: 12 },
        style: { fill: item.color },
      },
      {
        type: "text",
        right: 20,
        top: item.top,
        zlevel: 5,
        style: { text: item.text, fontSize: 12, fill: "#ffffff" },
      },
    ]);
  }
  return [];
});

// 6. 标签切换逻辑（无冗余）
const handleTabChange = (newTabIndex) => {
  currTabIndex.value = newTabIndex;
};

// 7. 加载地图数据（错误处理完善）
const loadMapData = async () => {
  try {
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

// 8. 获取情报区域数据（正常使用）
const getFir = async () => {
  const { code, data } = await firApi();
  return code === 200 ? data : null;
};

// 9. 详情标签点击逻辑（无未使用变量）
const handleDetail = (index) => {
  switch (index) {
    case "0":
      currTabIndex.value = isValidValue(props.airTestsObj.airportResults)
        ? "0"
        : "6";
      break;
    case "1":
      currTabIndex.value = isValidValue(props.airTests1Obj) ? "1" : "6";
      break;
    case "2":
      currTabIndex.value = isValidValue(props.airTestsAreaObj) ? "2" : "6";
      break;
    case "3":
      currTabIndex.value = isValidValue(props.airTestsRouteObj) ? "3" : "6";
      break;
    case "4":
    case "5":
      currTabIndex.value = index;
      break;
    default:
      currTabIndex.value = "6";
  }
};

// 10. 生成带缓冲的网格范围（无未定义变量）
const generateGridRange = (visibleRange) => {
  // 校验可视范围有效性
  const minLon = !isNaN(visibleRange.minLon) ? visibleRange.minLon : 70;
  const maxLon = !isNaN(visibleRange.maxLon) ? visibleRange.maxLon : 140;
  const minLat = !isNaN(visibleRange.minLat) ? visibleRange.minLat : 10;
  const maxLat = !isNaN(visibleRange.maxLat) ? visibleRange.maxLat : 60;

  const buffer = gridSize.value; // 缓冲步长=网格步长
  const step = gridSize.value;

  // 计算完整网格范围（2.5°整数倍）
  const calcMinLon = fixPrecision(Math.floor((minLon - buffer) / step) * step);
  const calcMaxLon = fixPrecision(Math.ceil((maxLon + buffer) / step) * step);
  const calcMinLat = fixPrecision(Math.floor((minLat - buffer) / step) * step);
  const calcMaxLat = fixPrecision(Math.ceil((maxLat + buffer) / step) * step);

  // 兜底：确保范围有效（min < max）
  return {
    minLon: calcMinLon < calcMaxLon ? calcMinLon : 67.5,
    maxLon: calcMinLon < calcMaxLon ? calcMaxLon : 142.5,
    minLat: calcMinLat < calcMaxLat ? calcMinLat : 7.5,
    maxLat: calcMinLat < calcMaxLat ? calcMaxLat : 62.5,
  };
};

// 11. 生成网格数据（无冗余逻辑）
const generateGridData = () => {
  const lines = [];
  const { minLon, maxLon, minLat, maxLat } = completeGridRange.value;
  const step = fixPrecision(gridSize.value) || 2.5; // 容错：步长无效时用默认值

  // 绘制纬线（横向线）
  let startLat = fixPrecision(Math.ceil(minLat / step) * step);
  let endLat = fixPrecision(Math.floor(maxLat / step) * step);
  startLat = startLat > endLat ? endLat : startLat;
  // 补充首尾边界线
  if (startLat > minLat) startLat = fixPrecision(startLat - step);
  if (endLat < maxLat) endLat = fixPrecision(endLat + step);
  // 最终容错
  startLat = !isNaN(startLat) ? startLat : 7.5;
  endLat = !isNaN(endLat) ? endLat : 62.5;

  for (let lat = startLat; lat <= endLat; lat = fixPrecision(lat + step)) {
    lines.push({
      type: "lines",
      name: `纬线_${lat}`,
      zlevel: 4,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
        vectorEffect: "non-scaling-stroke",
      },
      tooltip: { show: false },
      emphasis: { disabled: true },
      data: [
        [
          [minLon, lat],
          [maxLon, lat],
        ],
      ],
    });
  }

  // 绘制经线（纵向线）
  let startLon = fixPrecision(Math.ceil(minLon / step) * step);
  let endLon = fixPrecision(Math.floor(maxLon / step) * step);
  startLon = startLon > endLon ? endLon : startLon;
  // 补充首尾边界线
  if (startLon > minLon) startLon = fixPrecision(startLon - step);
  if (endLon < maxLon) endLon = fixPrecision(endLon + step);
  // 最终容错
  startLon = !isNaN(startLon) ? startLon : 67.5;
  endLon = !isNaN(endLon) ? endLon : 142.5;

  for (let lon = startLon; lon <= endLon; lon = fixPrecision(lon + step)) {
    lines.push({
      type: "lines",
      name: `经线_${lon}`,
      zlevel: 4,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: "rgba(0,59,122,1)",
        type: "solid",
        vectorEffect: "non-scaling-stroke",
      },
      tooltip: { show: false },
      emphasis: { disabled: true },
      data: [
        [
          [lon, minLat],
          [lon, maxLat],
        ],
      ],
    });
  }

  console.log(
    "绘制的网格线：",
    lines.map((l) => l.name)
  );
  return lines;
};

// 12. 绘制网格（无未使用变量）
const drawGrid = () => {
  if (!isReady.value || !chart.value) return;

  gridLines.value = generateGridData();
  const option = chart.value.getOption();
  const nonGridSeries =
    option.series?.filter(
      (series) =>
        !series.name?.startsWith("纬线_") && !series.name?.startsWith("经线_")
    ) || [];

  chart.value.setOption(
    {
      series: [...nonGridSeries, ...gridLines.value],
    },
    { replaceMerge: ["series"] }
  );
};

// 13. 计算geo适配参数（定义所有用到的变量）
const calculateGeoFit = (gridRange) => {
  const container = chartRef.value;
  if (!container) return { center: [104, 31], zoom: 1.2 };

  // 定义并校验容器宽高（修复 validWidth/validHeight 未定义问题）
  const { width: containerWidth, height: containerHeight } =
    container.getBoundingClientRect();
  const validWidth = containerWidth > 0 ? containerWidth : 1200;
  const validHeight = containerHeight > 0 ? containerHeight : 800;

  // 计算中心点（容错）
  const centerLon =
    !isNaN(gridRange.minLon) && !isNaN(gridRange.maxLon)
      ? fixPrecision((gridRange.minLon + gridRange.maxLon) / 2)
      : 104;
  const centerLat =
    !isNaN(gridRange.minLat) && !isNaN(gridRange.maxLat)
      ? fixPrecision((gridRange.minLat + gridRange.maxLat) / 2)
      : 31;

  // 计算缩放比例（容错）
  const lonRange =
    !isNaN(gridRange.minLon) && !isNaN(gridRange.maxLon)
      ? gridRange.maxLon - gridRange.minLon
      : 75; // 默认经度范围差
  const latRange =
    !isNaN(gridRange.minLat) && !isNaN(gridRange.maxLat)
      ? gridRange.maxLat - gridRange.minLat
      : 55; // 默认纬度范围差
  const validLonRange = lonRange > 0 ? lonRange : 75;
  const validLatRange = latRange > 0 ? latRange : 55;

  const lonScale = validWidth / (validLonRange * 1.1);
  const latScale = validHeight / (validLatRange * 1.1);
  const zoom = Math.min(lonScale, latScale) * 0.15;
  const validZoom = !isNaN(zoom) && zoom > 0 ? fixPrecision(zoom) : 1.2;

  console.log("geo参数：", { center: [centerLon, centerLat], zoom: validZoom });
  return {
    center: [centerLon, centerLat],
    zoom: validZoom,
    aspectRatio: validWidth / validHeight, // 返回宽高比，供后续使用
  };
};

// 14. 初始化图表（修复所有未定义变量，逻辑闭环）
const initChart = () => {
  if (!isReady.value || !chart.value || !chartRef.value) return;

  const container = chartRef.value;
  const { width: containerWidth, height: containerHeight } =
    container.getBoundingClientRect();
  console.log("容器尺寸：", { width: containerWidth, height: containerHeight });

  // 第一步：临时设置geo，获取真实可视范围
  chart.value.setOption(
    {
      geo: {
        map: "china",
        roam: false,
        emphasis: { disabled: true },
      },
    },
    { silent: true }
  );

  nextTick(async () => {
    try {
      // 定义四角经纬度（带默认值，避免转换失败）
      const topLeft = chart.value.convertFromPixel("geo", [10, 10]) || [70, 10];
      const topRight = chart.value.convertFromPixel("geo", [
        containerWidth - 10,
        10,
      ]) || [140, 10];
      const bottomLeft = chart.value.convertFromPixel("geo", [
        10,
        containerHeight - 10,
      ]) || [70, 60];
      const bottomRight = chart.value.convertFromPixel("geo", [
        containerWidth - 10,
        containerHeight - 10,
      ]) || [140, 60];

      // 过滤无效经纬度，计算可视范围
      const allLons = [
        topLeft[0],
        topRight[0],
        bottomLeft[0],
        bottomRight[0],
      ].filter((lon) => !isNaN(lon) && typeof lon === "number");
      const allLats = [
        topLeft[1],
        topRight[1],
        bottomLeft[1],
        bottomRight[1],
      ].filter((lat) => !isNaN(lat) && typeof lat === "number");

      visibleRange.value = {
        minLon: allLons.length > 0 ? fixPrecision(Math.min(...allLons)) : 70,
        maxLon: allLons.length > 0 ? fixPrecision(Math.max(...allLons)) : 140,
        minLat: allLats.length > 0 ? fixPrecision(Math.min(...allLats)) : 10,
        maxLat: allLats.length > 0 ? fixPrecision(Math.max(...allLats)) : 60,
      };
      console.log("可视范围：", visibleRange.value);

      // 第二步：计算完整网格范围
      completeGridRange.value = generateGridRange(visibleRange.value);
      console.log("完整网格范围：", completeGridRange.value);

      // 第三步：计算geo适配参数（包含aspectRatio）
      const { center, zoom, aspectRatio } = calculateGeoFit(
        completeGridRange.value
      );

      // 第四步：正式设置图表配置
      const option = {
        backgroundColor: "transparent",
        graphic: legendConfig.value,
        tooltip: {
          show: true,
          trigger: "item",
        },
        geo: {
          map: "china",
          longitudeRange: [
            completeGridRange.value.minLon,
            completeGridRange.value.maxLon,
          ],
          latitudeRange: [
            completeGridRange.value.minLat,
            completeGridRange.value.maxLat,
          ],
          center: center,
          zoom: zoom,
          roam: false,
          emphasis: { disabled: true },
          aspectRatio: aspectRatio, // 使用计算出的宽高比，避免未定义
          itemStyle: {
            normal: {
              borderColor: "#4896a4",
              borderWidth: 0.5,
              color: {
                type: "linear-gradient",
                x: 0,
                y: 1500,
                x2: 2500,
                y2: 0,
                colorStops: [
                  { offset: 0, color: "#132c5f" },
                  { offset: 1, color: "#132c5f" },
                ],
              },
              opacity: 0.5,
            },
            emphasis: {
              areaColor: "rgba(0, 157, 161, 0.5)",
              borderColor: "rgba(147, 235, 248, 1)",
            },
          },
          regions: [
            {
              name: "南海诸岛",
              itemStyle: {
                areaColor: "rgba(0, 10, 52, 1)",
                borderColor: "rgba(0, 10, 52, 1)",
              },
            },
          ],
          z: 1,
        },
        series: [
          {
            type: "map",
            map: "china",
            tooltip: { show: false },
            label: { show: false },
            center: center,
            zoom: zoom,
            roam: false,
            emphasis: { disabled: true },
            itemStyle: {
              normal: {
                borderColor: "rgba(147, 235, 248, 0.6)",
                borderWidth: 0.8,
                color: {
                  type: "linear-gradient",
                  x: 0,
                  y: 1200,
                  x2: 1000,
                  y2: 0,
                  colorStops: [
                    { offset: 0, color: "#132c5f" },
                    { offset: 1, color: "#132c5f" },
                  ],
                },
              },
              emphasis: {
                areaColor: "rgba(0, 157, 161, 0.5)",
                borderColor: "rgba(147, 235, 248, 0.6)",
              },
            },
            zlevel: 0,
          },
        ],
      };

      chart.value.setOption(option, {
        replaceMerge: ["geo", "series"],
        silent: false,
      });

      // 等待渲染后绘制网格和机场
      await new Promise((resolve) => setTimeout(resolve, 200));
      drawGrid();
      updateAirports();
      isFirstLoad.value = false;
      bindAirportDoubleClick();
    } catch (error) {
      console.error("初始化失败，使用默认配置：", error);
      // 兜底默认配置（无任何未定义变量）
      const defaultOption = {
        backgroundColor: "transparent",
        graphic: legendConfig.value,
        tooltip: { show: true, trigger: "item" },
        geo: {
          map: "china",
          longitudeRange: [67.5, 142.5],
          latitudeRange: [7.5, 62.5],
          center: [104, 31],
          zoom: 1.2,
          roam: false,
          emphasis: { disabled: true },
          aspectRatio: containerWidth / containerHeight || 1.5, // 容错
          itemStyle: {
            normal: {
              borderColor: "#4896a4",
              borderWidth: 0.5,
              color: "#132c5f",
              opacity: 0.5,
            },
            emphasis: {
              areaColor: "rgba(0, 157, 161, 0.5)",
              borderColor: "rgba(147, 235, 248, 1)",
            },
          },
          regions: [
            {
              name: "南海诸岛",
              itemStyle: {
                areaColor: "rgba(0, 10, 52, 1)",
                borderColor: "rgba(0, 10, 52, 1)",
              },
            },
          ],
          z: 1,
        },
        series: [
          {
            type: "map",
            map: "china",
            tooltip: { show: false },
            label: { show: false },
            center: [104, 31],
            zoom: 1.2,
            roam: false,
            emphasis: { disabled: true },
            itemStyle: {
              normal: {
                borderColor: "rgba(147, 235, 248, 0.6)",
                borderWidth: 0.8,
                color: "#132c5f",
              },
              emphasis: {
                areaColor: "rgba(0, 157, 161, 0.5)",
                borderColor: "rgba(147, 235, 248, 0.6)",
              },
            },
            zlevel: 0,
          },
        ],
      };
      chart.value.setOption(defaultOption);
      await new Promise((resolve) => setTimeout(resolve, 200));
      drawGrid();
      updateAirports();
      bindAirportDoubleClick();
    }
  });
};

// 15. 机场数据筛选（无未使用变量）
const getFilteredData = (targetKey) => {
  const newData = JSON.parse(JSON.stringify(props.airTestsObj));
  const originalResults = newData.airportResults || {};
  const filteredResults = {};
  if (Object.prototype.hasOwnProperty.call(originalResults, targetKey)) {
    filteredResults[targetKey] = originalResults[targetKey];
  } else {
    console.log(`未找到机场数据：${targetKey}`);
  }
  newData.airportResults = filteredResults;
  return newData;
};

// 16. 按名称筛选机场（无冗余）
const filterAirportByAirportName = (originalData, targetName) => {
  const newData = JSON.parse(JSON.stringify(originalData));
  const originalAirportResults = newData.airportResults || {};
  const filteredAirportResults = {};
  Object.keys(originalAirportResults).forEach((code) => {
    if (originalAirportResults[code]?.airport?.name === targetName) {
      filteredAirportResults[code] = originalAirportResults[code];
    }
  });
  newData.airportResults = filteredAirportResults;
  return newData;
};

// 17. 按区域ID筛选（无未使用变量）
const filterByAirAreaName = (originalData, targetPointId) => {
  return originalData.filter((item) => item?.area?.pointId === targetPointId);
};

// 18. 绑定机场双击事件（正常使用）
const bindAirportDoubleClick = () => {
  if (!chart.value) return;
  chart.value.on("dblclick", (params) => {
    switch (params.seriesName) {
      case "airports":
        if (params.data?.isBigPlane) {
          airTestsObjSpa.value = getFilteredData(params.data.airportCode);
          currTabIndex.value = "0Spa";
        }
        break;
      case "parkingLots":
        airTestsObj1Spa.value = filterAirportByAirportName(
          props.airTests1Obj,
          params.data.name
        );
        currTabIndex.value = "1Spa";
        break;
      case "areaStaticStatRect":
        airTestsArea2Obj.value = filterByAirAreaName(
          props.airTestsAreaObj,
          params.data.area.pointId
        );
        currTabIndex.value = "2Spa";
        break;
    }
  });
};

// 19. 更新机场/区域/航线数据（无未使用变量）
const updateAirports = () => {
  if (!isReady.value || !chart.value) return;

  // 定义图片路径（确保使用正确）
  const greenPlane = new URL(
    "../../../assets/images/raim/airlvicon.png",
    import.meta.url
  ).href;
  const bigPlane = new URL(
    "../../../assets/images/raim/airlanbigicon.png",
    import.meta.url
  ).href;
  const planeLot = new URL(
    "../../../assets/images/raim/planelot.png",
    import.meta.url
  ).href;

  // 处理机场数据
  const airports1NameSet = new Set(
    props.airports1.map((item) => item.name?.trim())
  );
  const airportData = props.airports.map((airport) => ({
    name: airport.name,
    value: [airport.longitude, airport.latitude],
    isBigPlane: airports1NameSet.has(airport.name?.trim()),
    ...airport,
  }));
  const finalAirportData = [
    ...airportData.filter((item) => !item.isBigPlane),
    ...airportData.filter((item) => item.isBigPlane),
  ];

  const option = chart.value.getOption();
  const series = [...(option.series || [])];

  // 移除旧系列
  const removeSeries = (name) => {
    const index = series.findIndex((s) => s.name === name);
    if (index !== -1) series.splice(index, 1);
  };
  removeSeries("airports");
  removeSeries("parkingLots");
  removeSeries("areaStaticRect");
  removeSeries("areaStaticStatRect");
  removeSeries("routeWayPoints");

  // 添加机场系列
  series.push({
    type: "scatter",
    name: "airports",
    coordinateSystem: "geo",
    zlevel: 5,
    tooltip: {
      show: true,
      trigger: "item",
      padding: 12,
      backgroundColor: "rgba(0, 15, 40, 0.9)",
      borderColor: "rgba(147, 235, 248, 0.8)",
      borderWidth: 1,
      textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
      formatter: (params) => {
        if (params.data?.isBigPlane) {
          return `
            <div>
              <p><b>名称：</b>(${params.data.airportCode})${params.data.city}/${params.data.name}</p>
              <p><b>经度：</b>${params.data.longitude}</p>
              <p><b>纬度：</b>${params.data.latitude}</p>
              <p><b>海拔：</b>${params.data.elevation}</p>
            </div>
          `;
        }
        return "";
      },
    },
    data: finalAirportData.map((item) => ({
      ...item,
      symbol: `image://${item.isBigPlane ? bigPlane : greenPlane}`,
      symbolSize: item.isBigPlane ? [36, 60] : [18, 30],
      zlevel: item.isBigPlane ? 10 : 5,
    })),
  });

  // 添加机场终端区系列
  if (isValidValue(props.airports2)) {
    series.push({
      type: "scatter",
      name: "parkingLots",
      coordinateSystem: "geo",
      zlevel: 6,
      tooltip: {
        show: true,
        trigger: "item",
        padding: 12,
        backgroundColor: "rgba(0, 15, 40, 0.9)",
        borderColor: "rgba(147, 235, 248, 0.8)",
        borderWidth: 1,
        textStyle: { color: "#fff", fontSize: 13, lineHeight: 1.5 },
        formatter: (params) => `
          <div>
            <p><b>名称：</b>(${params.data.airportCode})${params.data.city}/${params.data.name}</p>
            <p><b>经度：</b>${params.data.longitude}</p>
            <p><b>纬度：</b>${params.data.latitude}</p>
            <p><b>海拔：</b>${params.data.elevation}</p>
          </div>
        `,
      },
      data: props.airports2.map((parking) => ({
        ...parking,
        symbol: `image://${planeLot}`,
        symbolSize: [24, 40],
        zlevel: 6,
      })),
    });
  }

  // 添加静态区域（不可用）系列
  if (isValidValue(props.areaStatic)) {
    const { width: containerWidth } = chartRef.value.getBoundingClientRect();
    const geoModel = chart.value.getModel().getComponent("geo");
    const [visMinLon, visMaxLon] = geoModel?.option?.longitudeRange || [
      73, 135,
    ];
    const lonRange = visMaxLon - visMinLon;
    const pixelToLon = containerWidth > 0 ? lonRange / containerWidth : 0.1;
    const pixelToLat = pixelToLon;
    const offsetLon = 18 * pixelToLon;
    const offsetLat = 18 * pixelToLat;

    series.push({
      type: "scatter",
      name: "areaStaticRect",
      coordinateSystem: "geo",
      zlevel: 4,
      symbol: "rect",
      symbolSize: [22, 32],
      itemStyle: { color: "rgba(255,0,0,0.4)" },
      tooltip: {
        show: true,
        trigger: "item",
        position: (point) => {
          const tooltipWidth = 120;
          return [Math.max(point[0] - tooltipWidth - 10, 10), point[1]];
        },
        textStyle: { textAlign: "left" },
        formatter: (params) => `
          <div style="text-align: left !important;">
            <p><b>经度：</b>${params.data.area.longitude}</p>
            <p><b>纬度：</b>${params.data.area.latitude}</p>
            <p><b>海拔：</b>${params.data.area.elevation}</p>
          </div>
        `,
      },
      data: props.areaStatic.map((item) => {
        const { longitude: lon, latitude: lat } = item.area;
        const baseAlignedLon =
          Math.round(lon / gridSize.value) * gridSize.value;
        const baseAlignedLat =
          Math.round(lat / gridSize.value) * gridSize.value;
        return {
          name: `静态区域${item.pointId}`,
          value: [baseAlignedLon + offsetLon, baseAlignedLat + offsetLat],
          ...item,
        };
      }),
    });
  }

  // 添加静态区域统计系列
  if (isValidValue(props.areaStatic1)) {
    const { width: containerWidth } = chartRef.value.getBoundingClientRect();
    const geoModel = chart.value.getModel().getComponent("geo");
    const [visMinLon, visMaxLon] = geoModel?.option?.longitudeRange || [
      73, 135,
    ];
    const lonRange = visMaxLon - visMinLon;
    const pixelToLon = containerWidth > 0 ? lonRange / containerWidth : 0.1;
    const pixelToLat = pixelToLon;
    const offsetLon = 18 * pixelToLon;
    const offsetLat = 18 * pixelToLat;

    const colorLevelMap = {
      0: "#7cfa8d",
      1: "#4dad51",
      2: "#2f7132",
      3: "#d7fc62",
      4: "#fcfe54",
      5: "#f8cf59",
      6: "#f19135",
      7: "#ee692c",
      8: "#ec3323",
    };

    series.push({
      type: "scatter",
      name: "areaStaticStatRect",
      coordinateSystem: "geo",
      zlevel: 4,
      symbol: "rect",
      symbolSize: [22, 32],
      itemStyle: {
        color: (params) =>
          colorLevelMap[params.data.colorLevel] || "rgba(200, 200, 200, 0.4)",
      },
      tooltip: {
        show: true,
        trigger: "item",
        formatter: (params) => `
          <div>
            <p><b>经度：</b>${params.data.area.longitude}</p>
            <p><b>纬度：</b>${params.data.area.latitude}</p>
            <p><b>海拔：</b>${params.data.area.elevation}</p>
          </div>
        `,
      },
      data: props.areaStatic1.map((item) => {
        const { longitude: lon, latitude: lat } = item.area;
        const baseAlignedLon =
          Math.round(lon / gridSize.value) * gridSize.value;
        const baseAlignedLat =
          Math.round(lat / gridSize.value) * gridSize.value;
        return {
          name: `静态区域${item.pointId}`,
          value: [baseAlignedLon + offsetLon, baseAlignedLat + offsetLat],
          ...item,
        };
      }),
    });
  }

  // 添加航线系列
  if (isValidValue(props.routeWayPoints) && props.routeWayPoints.length > 1) {
    const validCoords = props.routeWayPoints.map((point) => [
      point.longitude,
      point.latitude,
    ]);
    series.push({
      type: "lines",
      name: "routeWayPoints",
      zlevel: 7,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: { width: 1, color: "#72e789", opacity: 1.0, dashOffset: 5 },
      data: [{ name: "航线", coords: validCoords }],
    });
  }

  // 更新图表
  chart.value.setOption(
    { series },
    { replaceMerge: ["series"], silent: false }
  );
};

// 20. 强制更新图例（无未使用变量）
const forceUpdateGraphic = () => {
  if (!isReady.value || !chart.value) return;
  chart.value.setOption(
    { graphic: legendConfig.value },
    { silent: false, replaceMerge: ["graphic"] }
  );
};

// 21. 监听数据变化（正常使用）
watch(
  () => [
    props.airports,
    props.airports1,
    props.airports2,
    props.areaStatic,
    props.areaStatic1,
    props.routeWayPoints,
  ],
  async () => {
    forceUpdateGraphic();
    await new Promise((resolve) => setTimeout(resolve, 20));
    updateAirports();
  },
  { deep: true }
);

// 22. 监听情报区域复选框（无未使用变量）
watch(
  areaChecked,
  async (isChecked) => {
    if (!isReady.value || !chart.value) return;

    const option = chart.value.getOption();
    const series = [...(option.series || [])];
    // 移除旧路径系列
    const pathIndex = series.findIndex((s) => s.name === pathSeriesName);
    if (pathIndex !== -1) series.splice(pathIndex, 1);

    if (isChecked) {
      const simulateData = await getFir();
      if (isValidValue(simulateData)) {
        pathData.value = simulateData;
        const pathSeriesList = simulateData
          .filter(
            (item) =>
              item?.shapePoints &&
              Array.isArray(item.shapePoints) &&
              item.shapePoints.length > 1
          )
          .map((item) => ({
            type: "lines",
            name: pathSeriesName,
            zlevel: 7,
            coordinateSystem: "geo",
            polyline: true,
            lineStyle: {
              width: 1,
              color: "#00AFFF",
              opacity: 1.0,
              dashOffset: 5,
              type: "dashed",
            },
            tooltip: {
              show: true,
              formatter: () => `路径：${item.identifier || "未知区域"}`,
            },
            data: [
              {
                name: item.identifier || "未知区域",
                coords: item.shapePoints.map((p) => [p.longitude, p.latitude]),
              },
            ],
          }));
        series.push(...pathSeriesList);
      }
    } else {
      pathData.value = [];
    }

    chart.value.setOption(
      { series },
      { replaceMerge: ["series"], silent: false }
    );
  },
  { immediate: false }
);

// 23. 窗口resize处理（无未定义变量）
const handleWindowResize = debounce(() => {
  console.log("窗口变化，重新初始化");
  if (isReady.value && chart.value && chartRef.value) {
    try {
      chart.value.clear();
      isFirstLoad.value = true;
      initChart();
    } catch (error) {
      console.error("resize失败：", error);
      initChart();
    }
  }
}, 300);

// 24. 组件挂载初始化（无未使用变量）
onMounted(() => {
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      // 初始化ECharts实例
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas",
        useDirtyRect: true,
        devicePixelRatio: window.devicePixelRatio || 1,
      });
      // 加载地图数据
      const dataLoaded = await loadMapData();
      if (dataLoaded) {
        isReady.value = true;
        initChart();
      } else {
        console.error("地图加载失败，无法初始化图表");
      }
    });
  }, 100);
  // 绑定窗口resize事件
  window.addEventListener("resize", handleWindowResize);
});

// 25. 监听容器宽度变化（正常使用）
watch(
  () => chartRef.value?.clientWidth,
  (newWidth, oldWidth) => {
    if (newWidth && oldWidth && Math.abs(newWidth - oldWidth) > 50) {
      console.log("容器宽度变化，重新适配", { oldWidth, newWidth });
      if (isReady.value) {
        handleWindowResize();
      }
    }
  },
  { immediate: false }
);

// 26. 组件卸载清理（无未使用变量）
onUnmounted(() => {
  if (chart.value) {
    chart.value.off("dblclick");
    chart.value.dispose();
    chart.value = null;
  }
  window.removeEventListener("resize", handleWindowResize);
  isReady.value = false;
  pathData.value = [];
});
</script>

<style scoped lang="scss">
.mapCheckedBox {
  position: absolute;
  left: 20px;
  z-index: 10;
  top: 7px;
  .white-text-checkbox :deep(.el-checkbox__label) {
    color: #ffffff !important;
    font-size: 12px;
  }
}

.mapTabs {
  width: 650px;
  height: 44px;
  margin: 0 auto;
  margin-top: 10px;
  position: relative;
  z-index: 10;
  .tab {
    cursor: pointer;
    float: left;
    margin-right: 8px;
    color: #c5d6e6;
    font-size: 12px;
    text-align: center;
    width: 100px;
    height: 44px;
    line-height: 44px;
    background-image: url("../../../assets/images/raim/tabUnChange.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
  .tabs {
    padding: 0 15px;
    line-height: 22px;
  }
  .tabs1 {
    padding: 0 21px;
    line-height: 22px;
  }
  .tabCur {
    color: #fff;
    background-image: url("../../../assets/images/raim/tabChange.png");
  }
}

.map-container {
  position: relative;
  margin-top: 30px;
  margin-left: 30px;
  width: calc(100% - 30px);
  height: calc(100% - 90px);
  box-sizing: border-box;
  max-width: calc(100% - 30px);
  max-height: 100%;
  overflow: visible !important;
}

.chart-container {
  width: 100%;
  height: 100%;
  background: transparent;
  overflow: visible !important;
  position: relative;
  z-index: 1;
}

// 确保网格线不被遮挡、不变形
:deep(.ec-plot) {
  transition: all 0.3s ease;
  overflow: visible !important;
}
:deep(.ec-geo) {
  overflow: visible !important;
  .ec-geo-area {
    fill: #132c5f;
    fill-opacity: 0.5;
    stroke: #4896a4;
    stroke-width: 0.5;
  }
  .ec-geo-region[name="南海诸岛"] {
    fill: rgba(0, 10, 52, 1);
    stroke: rgba(0, 10, 52, 1);
  }
}
:deep(.ec-series-lines) {
  stroke: rgba(0, 59, 122, 1);
  stroke-width: 1;
  vector-effect: non-scaling-stroke !important;
  overflow: visible !important;
}
:deep(.ec-series-scatter) {
  .ec-scatter-item {
    transition: transform 0.2s ease;
  }
  .ec-scatter-item:hover {
    transform: scale(1.05);
  }
}
:deep(.ec-series-lines[name="simulatePath"]) {
  stroke: #00afff;
  stroke-width: 1;
  stroke-dasharray: 5, 5;
  stroke-opacity: 1;
  vector-effect: non-scaling-stroke !important;
}
</style>
